//
//  YJScreenControl.m
//  CToolBox
//
//  Created by crj on 16/8/24.
//  Copyright © 2016年 oyf. All rights reserved.
//

#import "YJScreenControl.h"
#import "UIImage+compressIMG.h"


CGFloat const contentViewWidth = 270;
CGFloat const btnContentViewHeight = 60;
CGFloat const itemHeight = 25;
CGFloat const itemMinWidth = (contentViewWidth-kSpaceSide*4)/3;
CGFloat const itemFont = 14;

CGFloat const sideSpace = 5;//item 距离collectionView左右的大小
NSInteger const minDisplays = 15;//每组最少显示数


@interface YJScreenControl()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>

/** 城市列表 */
@property (nonatomic, strong) NSMutableArray *cityArray;
/** 行业列表 */
@property (nonatomic, strong) NSMutableArray *industryArray;

//所有内容载体
@property (nonatomic, strong) UIView *contentView;
//状态栏背景视图
@property (nonatomic, strong) UIView *statueView;
//筛选条件列表
@property (nonatomic, strong) UICollectionView *collectionView;
//按钮载体
@property (nonatomic, strong) UIView *btnContentView;


//打开状态
@property (nonatomic, assign) BOOL isOpenCity;
@property (nonatomic, assign) BOOL isOpenTrade;

@property (nonatomic, copy) ScreenControlComplete complete;



@end

@implementation YJScreenControl
+ (YJScreenControl *)showScreenControlWithCitys:(NSArray *)citys trades:(NSArray *)trades complete:(ScreenControlComplete)complete{
    
    YJScreenControl *screenControl = [[YJScreenControl alloc] initWithCitys:citys trades:trades complete:complete];
    [[UIApplication sharedApplication].keyWindow addSubview:screenControl];
    
    [screenControl show];
    
    return screenControl;

}

- (instancetype)initWithCitys:(NSArray *)citys trades:(NSArray *)trades complete:(ScreenControlComplete)complete
{
    self = [super init];
    if (self) {
        
        _cityArray = [[NSMutableArray alloc] init];
        _industryArray = [[NSMutableArray alloc] init];
        
        for(ProvincesEntity *key in citys){
            YJScreenControlItemModel *model = [[YJScreenControlItemModel alloc] init];
            model.key = key.Name;
            model.isSelect = NO;
            [_cityArray addObject:model];
        }
        for(IndustriesEntity *key in trades){
            YJScreenControlItemModel *model = [[YJScreenControlItemModel alloc] init];
            model.key = key.Name;
            model.isSelect = NO;
            [_industryArray addObject:model];
        }


        _complete = complete;
        [self setConfig];
        [self makeUI];
    }
    return self;
}



- (void)setConfig{
    
    
    _isOpenCity = NO;
    _isOpenTrade = NO;
    
    self.frame = [UIApplication sharedApplication].keyWindow.bounds;
    self.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0];
    [self addTarget:self action:@selector(close) forControlEvents:UIControlEventTouchUpInside];
}

-(void)makeUI{
    
    _contentView = [[UIView alloc] init];
    _contentView.frame = CGRectMake(-contentViewWidth, 0, contentViewWidth, HEIGHT);
    _contentView.backgroundColor = [UIColor whiteColor];
    [self addSubview:_contentView];
    
    _statueView = [[UIView alloc] init];
    _statueView.frame = CGRectMake(0, 0, contentViewWidth, 20);
    _statueView.backgroundColor = HEXCOLOR(kColorBlue1, 1);
    [_contentView addSubview:_statueView];
    
    /** 数据展示区 */
    UICollectionViewFlowLayout *layoutView = [[UICollectionViewFlowLayout alloc] init];
    CGRect frame = CGRectMake(kSpaceSide/2, _statueView.frame.size.height, _contentView.frame.size.width-kSpaceSide, _contentView.frame.size.height-20-btnContentViewHeight);
    _collectionView = [[UICollectionView alloc] initWithFrame:frame collectionViewLayout:layoutView];
    _collectionView.backgroundColor = [UIColor clearColor];
    _collectionView.showsVerticalScrollIndicator = NO;
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    [_contentView addSubview:_collectionView];
    
    
    // 注册cell、sectionHeader、sectionFooter
    [_collectionView registerClass:[YJScreenControlCell class] forCellWithReuseIdentifier:@"cell"];
    [_collectionView registerClass:[YJScreenControlHeader class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header"];
    [_collectionView registerClass:[YJScreenControlFooter class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"footer"];
    
    /** btn */
    _btnContentView = [[UIView alloc] init];
    _btnContentView.frame = CGRectMake(0, _contentView.frame.size.height- btnContentViewHeight, _contentView.frame.size.width, btnContentViewHeight);
    [_contentView addSubview:_btnContentView];
    
    UIButton *resetBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [resetBtn setTitleColor:HEXCOLOR(kColorBlue1, 1) forState:UIControlStateNormal];
    resetBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    [resetBtn setTitle:@"重置" forState:UIControlStateNormal];
    resetBtn.layer.masksToBounds = YES;
    resetBtn.layer.borderColor = HEXCOLOR(kColorBlue1, 1).CGColor;
    resetBtn.layer.borderWidth = 1;
    resetBtn.layer.cornerRadius = kCornerRadius;
    
    UIButton *completeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    completeBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    [completeBtn setTitle:@"完成" forState:UIControlStateNormal];
    [completeBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    completeBtn.backgroundColor = HEXCOLOR(kColorBlue1, 1);
    completeBtn.layer.masksToBounds = YES;
    completeBtn.layer.cornerRadius = kCornerRadius;
    
    //btn frame
    CGFloat btnWidth = 90.0;
    CGFloat btnHeight = 30.0;
    CGFloat btnSpace = 15.0;
    resetBtn.frame = CGRectMake(contentViewWidth/2-btnSpace/2-btnWidth, 0, btnWidth, btnHeight);
    completeBtn.frame = CGRectMake(contentViewWidth/2+btnSpace/2, 0, btnWidth, btnHeight);
    resetBtn.center = CGPointMake(resetBtn.center.x, btnContentViewHeight/2);
    completeBtn.center = CGPointMake(completeBtn.center.x, btnContentViewHeight/2);
    
    [_btnContentView addSubview:resetBtn];
    [_btnContentView addSubview:completeBtn];
    
    [resetBtn addTarget:self action:@selector(resetAction) forControlEvents:UIControlEventTouchUpInside];
    [completeBtn addTarget:self action:@selector(completeAction) forControlEvents:UIControlEventTouchUpInside];
}

- (void)show{
    
    [UIView animateWithDuration:0.5 animations:^{
        self.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.2];
        _contentView.frame = CGRectMake(0, 0, contentViewWidth, self.frame.size.height);
    }];
    
}

- (void)close{
    
    [UIView animateWithDuration:0.5 animations:^{
        self.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0];
        _contentView.frame = CGRectMake(-contentViewWidth, 0, contentViewWidth, self.frame.size.height);
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
}

#pragma mark Event Respond

- (void)resetAction{
    
    NSLog(@"重置");
    for(YJScreenControlItemModel *model in _cityArray){
        model.isSelect = NO;
    }
    for(YJScreenControlItemModel *model in _industryArray){
        model.isSelect = NO;
    }
    
    [_collectionView reloadData];
    
}

- (void)completeAction{
    
    if(_complete){
        _complete([self spliceWithKeys:_cityArray],[self spliceWithKeys:_industryArray]);
    }
    [self close];
}

#pragma mark - UICollectionViewDataSource

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    
    return 2;
}



- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    if(section == 0){//城市

        return [self cityDisplayNum];
    }else{//行业
        
        return [self tradeDisPlayNum];
    }
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    YJScreenControlItemModel *model;
    if(indexPath.section == 0){
        model = _cityArray[indexPath.row];
    }else{
        model = _industryArray[indexPath.row];
    }
    
    YJScreenControlCell *cell = [_collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];


        [cell.button setTitle:model.key forState:UIControlStateNormal];
        cell.button.selected = model.isSelect;
        
    
    return cell;
}


- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    
    if([kind isEqualToString:UICollectionElementKindSectionHeader]){
        YJScreenControlHeader *view = [_collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"header" forIndexPath:indexPath];
        if(indexPath.section == 0){
            view.titleLabel.text = @"按地域分";
        }else{
            view.titleLabel.text = @"按行业分";
        }

        return view;
        
    }else if([kind isEqualToString:UICollectionElementKindSectionFooter]){
        
        YJScreenControlFooter *footer = [_collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"footer" forIndexPath:indexPath];
        footer.openBtn.tag = indexPath.section;
        if(indexPath.section == 0){
            footer.openBtn.selected = _isOpenCity;
        }else{
            footer.openBtn.selected = _isOpenTrade;
        }
        
        footer.selectBlock = ^(NSInteger section){
            if(section == 0){
                self.isOpenCity = !_isOpenCity;
               
            }else{
               self.isOpenTrade = !_isOpenTrade;
            }

        };
        return footer;
    }
    return nil;
}



#pragma mark - UICollectionViewDelegateFlowLayout

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    CGFloat itemWidth = [self itemWidthWithIndexPath:indexPath];
    return (CGSize){itemWidth,itemHeight};
}
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    
    return UIEdgeInsetsMake(5, 5, 5, 5);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    
    return 5;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    
    return 5;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section{
    
    BOOL isNeedShow;
    if(section == 0){
        isNeedShow = [self isNeedFooter:_cityArray];
    }else{
        isNeedShow = [self isNeedFooter:_industryArray];
    }
    if(isNeedShow){
        return (CGSize){contentViewWidth,44};

    }else{
        return (CGSize){0,0};
    }
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    
    return (CGSize){_contentView.frame.size.width,44};
}

#pragma mark - UICollectionViewDelegate

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    YJScreenControlCell *cell = (YJScreenControlCell *)[collectionView cellForItemAtIndexPath:indexPath];
    
    NSArray *tempArray;
    if(indexPath.section == 0){
        tempArray = _cityArray;
    }else if(indexPath.section == 1){
        tempArray = _industryArray;
    }
    YJScreenControlItemModel *model = tempArray[indexPath.row];
    model.isSelect = !model.isSelect;
    
    cell.button.selected = model.isSelect;
}

#pragma mark - private

//是否需要显示展开按钮 (判断是否需要footer)
- (BOOL)isNeedFooter:(NSArray *)array{
    
    if(array.count>minDisplays){
        return YES;
    }else{
        return NO;
    }
}

- (NSInteger)tradeDisPlayNum{
    
    NSInteger number;
    if([self isNeedFooter:_industryArray]){//大于最小数
        number = _isOpenTrade?_industryArray.count:minDisplays;
    }else{//小于等于最小数
        number = _industryArray.count;
    }
    return number;
}

- (NSInteger)cityDisplayNum{
    
    NSInteger number;
    if([self isNeedFooter:_cityArray]){//大于最小数
        number =  _isOpenCity?_cityArray.count:minDisplays;
    }else{//小于等于最小数
        number = _cityArray.count;
    }
    
    return number;
}

#pragma mark - Private

- (CGFloat)itemWidthWithIndexPath:(NSIndexPath *)indexPath{
    
    UIFont *font = [UIFont systemFontOfSize:itemFont];

    if(indexPath.section == 0){
        YJScreenControlItemModel *city = _cityArray[indexPath.row];
       return [self returnLabelWidthWithString:city.key font:font];
    }else{
//        YJScreenControlItemModel *industry = _industryArray[indexPath.row];
        return contentViewWidth-kSpaceSide*2;

    }

}

//返回宽度
- (CGFloat)returnLabelWidthWithString:(NSString *)string font:(UIFont *)font
{
    
    //至少需要的宽度
    CGFloat needWidth = [Utils widthOfString:string font:font height:20]+20;
    
    return needWidth>itemMinWidth?needWidth:itemMinWidth;
    
}

//拼接关键字（以逗号分隔）
- (NSString *)spliceWithKeys:(NSArray <YJScreenControlItemModel *>*)keys{
    
    NSPredicate *pre = [NSPredicate predicateWithFormat:@"isSelect == YES"];
    NSArray *selectArray=[keys filteredArrayUsingPredicate: pre];

    
    NSString *string = @"";
    if(selectArray.count == 0){
        return string;
    }
    
    YJScreenControlItemModel *model = selectArray[0];
    string = model.key;
    for(int i=1; i<selectArray.count; i++){
        YJScreenControlItemModel *model = selectArray[i];
        string = [NSString stringWithFormat:@"%@,%@",string,model.key];
    }
    return string;
}


#pragma mark - SET

- (void)setIsOpenCity:(BOOL)isOpenCity{
    
    _isOpenCity = isOpenCity;
    
    
    //动画
    NSMutableArray *array = [[NSMutableArray alloc] init];
    for(int i=minDisplays; i<_cityArray.count; i++){
        NSIndexPath *index = [NSIndexPath indexPathForRow:i inSection:0];
        [array addObject:index];
    }
    
    if(_isOpenCity){
        [_collectionView insertItemsAtIndexPaths:array];
    }else{
        
        [_collectionView deleteItemsAtIndexPaths:array];
    }
    
}

- (void)setIsOpenTrade:(BOOL)isOpenTrade{
    _isOpenTrade = isOpenTrade;
    
    //动画
    NSMutableArray *array = [[NSMutableArray alloc] init];
    for(int i=minDisplays; i<_industryArray.count; i++){
        NSIndexPath *index = [NSIndexPath indexPathForRow:i inSection:1];
        [array addObject:index];
    }
    
    if(_isOpenTrade){
        [_collectionView insertItemsAtIndexPaths:array];
    }else{
        [_collectionView deleteItemsAtIndexPaths:array];
    }
    
}




/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end



#pragma mark -------------- UICollectionView SubView Class ----------------

@implementation YJScreenControlCell

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        _button = [UIButton buttonWithType:UIButtonTypeCustom];
        _button.tintColor = [UIColor clearColor];
        _button.backgroundColor = [UIColor clearColor];
        _button.titleLabel.font = [UIFont systemFontOfSize:itemFont];
        [_button setTitleColor:HEXCOLOR(kColorBlue5, 1) forState:UIControlStateNormal];
        [_button setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
        _button.layer.masksToBounds = YES;
        _button.layer.cornerRadius = kCornerRadius;
        _button.layer.borderColor = HEXCOLOR(kColorBlue5, 1).CGColor;
        _button.layer.borderWidth = 0.5;
        
        UIImage *selectImage = [UIImage createImageWithColor:HEXCOLOR(kColorBlue1, 1)];
        [_button setBackgroundImage:selectImage forState:UIControlStateSelected];
    
        
        UIView *clearView = [[UIView alloc] init];
        clearView.frame = CGRectMake(0, 0, 300, 300);
        clearView.backgroundColor = [UIColor clearColor];
        [self.contentView addSubview:_button];
        [self.contentView addSubview:clearView];

    }
    return self;
}

- (void)layoutSubviews{
    
    [super layoutSubviews];
    _button.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
}

@end

@implementation YJScreenControlHeader

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
        _titleLabel = [[UILabel alloc] init];
        _titleLabel.textColor = HEXCOLOR(kColorGray1, 1);
        _titleLabel.font = [UIFont systemFontOfSize:14];
        [self addSubview:_titleLabel];
        
        _lineLabel = [[UILabel alloc] init];
        _lineLabel.backgroundColor = HEXCOLOR(kColorGray7, 1);
        [self addSubview:_lineLabel];
    }
    return self;
}

- (void)layoutSubviews{
    
    [super layoutSubviews];
    _titleLabel.frame = CGRectMake(sideSpace, 0, self.frame.size.width-sideSpace*2, self.frame.size.height);
    _lineLabel.frame = CGRectMake(sideSpace, self.frame.size.height-0.5, self.frame.size.width-sideSpace*2, 0.5);
}

@end

@implementation YJScreenControlFooter

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {

        NSString *normalTitle = [NSString stringWithFormat:@"%@ 展开",theIconFont.iconxiajiantou];
        NSString *selectedTitle = [NSString stringWithFormat:@"%@ 收起",theIconFont.iconshangjiantou];

        
        
        _openBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_openBtn setTitleColor:HEXCOLOR(kColorGray1, 1) forState:UIControlStateNormal];
        [_openBtn setTitle:normalTitle forState:UIControlStateNormal];
        [_openBtn setTitle:selectedTitle forState:UIControlStateSelected];
        _openBtn.titleLabel.font = [UIFont fontWithName:kFontIcon size:14];
        [_openBtn sizeToFit];
        [_openBtn addTarget:self action:@selector(openAction:) forControlEvents:UIControlEventTouchUpInside];
        _openBtn.backgroundColor = [UIColor clearColor];
        [self addSubview:_openBtn];
        
    }
    return self;
}

- (void)openAction:(UIButton *)btn{
    
    btn.selected = !btn.selected;
    if(_selectBlock){
        _selectBlock(btn.tag);
    }
}

- (void)layoutSubviews{
    
    [super layoutSubviews];
    _openBtn.center = CGPointMake(self.frame.size.width-sideSpace-_openBtn.frame.size.width/2, self.frame.size.height/2);
}

@end

@implementation YJScreenControlItemModel


@end




